package summary;

import javax.script.ScriptException;
import java.util.LinkedList;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/11 11:54
 * https://leetcode-cn.com/problems/fraction-addition-and-subtraction/
 */
public class Title592 {

    public static String fractionAddition(String expression){
        LinkedList<Character> sign = new LinkedList<>();
        if (expression.charAt(0) != '-') {
            sign.offer('+');
        }
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (c == '+' || c == '-') {
                sign.offer(c);
            }
        }
        int upNum = 0;
        int downNum = 1;
        for (String s: expression.split("(\\+)|-")) {
                if (s.length() != 0) {
                    String[] split = s.split("/");
                    Integer a = Integer.valueOf(split[0]);
                    Integer b = Integer.valueOf(split[1]);
                    Character poll = sign.poll();
                    //求最大公约数
                    int gcm = Math.abs(gCM(downNum, b));
                    if (poll == '-') {
                        upNum = upNum * b / gcm - a * downNum / gcm;
                    }else{
                        upNum = upNum * b / gcm + a * downNum / gcm;
                    }
                    downNum = downNum * b / gcm;
                    //约分
                    gcm = Math.abs(gCM(upNum, downNum));
                    upNum /= gcm;
                    downNum /= gcm;
                }
        }
        return upNum + "/" + downNum;
    }



    /**
     * 求a、b的最大公约数
     * @param a
     * @param b
     * @return
     */
    private static int gCM(int a, int b) {
        //求最大公约数（辗转相除法）
        int c = a % b;
        while (c != 0) {
            a = b;
            b = c;
            c = a % b;
        }
        return b;
    }

    public static void main(String[] args) throws ScriptException {
        String s = fractionAddition("-1/2+1/2");
        System.out.println(s);
    }
}
